package com.ruoyi.womp.socket;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.womp.config.WebsocketConst;

@Component
@ServerEndpoint("/womp_wa/{wacode}")
public class WompWebSocket {

	private Session session;

	private String wacode;

	private static CopyOnWriteArraySet<WompWebSocket> webSockets = new CopyOnWriteArraySet<>();
	private static Map<String, Session> sessionPool = new HashMap<String, Session>();

	@OnOpen
	public void onOpen(Session session, @PathParam(value = "wacode") String wacode) {
		try {
			this.session = session;
			this.wacode = wacode;
			webSockets.add(this);
			sessionPool.put(wacode + "-" + session.getId(), session);
			// log.info("【websocket消息】有新的连接，总数为:" + webSockets.size());
		} catch (Exception e) {
		}
	}

	@OnClose
	public void onClose() {
		try {
			webSockets.remove(this);
			sessionPool.remove(this.wacode + "-" + session.getId());
			// log.info("【websocket消息】连接断开，总数为:" + webSockets.size());
		} catch (Exception e) {
		}
	}

	/**
	 * 服务端推送消息
	 *
	 * @param wacode
	 * @param message
	 */
	public void pushMessage(String wacode, String message) {
		for (WompWebSocket wompWebSocket : webSockets) {
			if (wompWebSocket.wacode.equals(wacode)) {
				Session session = sessionPool.get(wacode + "-" + wompWebSocket.session.getId());
				if (session != null && session.isOpen()) {
					synchronized (session) {
						try {
							// log.info("【websocket消息】 单点消息:" + message);
							session.getBasicRemote().sendText(message);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
	}

	/**
	 * 服务器端推送消息
	 */
	public void pushMessage(String message) {
		try {
			webSockets.forEach(ws -> ws.session.getAsyncRemote().sendText(message));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@OnMessage
	public void onMessage(String message) {
		// todo 现在有个定时任务刷，应该去掉
		// log.debug("【websocket消息】收到客户端消息:" + message);
		JSONObject obj = new JSONObject();
		// 业务类型
		obj.put(WebsocketConst.MSG_CMD, WebsocketConst.CMD_CHECK);
		// 消息内容
		obj.put(WebsocketConst.MSG_TXT, "心跳响应");
		for (WompWebSocket webSocket : webSockets) {
			webSocket.pushMessage(message);
		}
	}
}